<template>
  <!-- 导航栏 -->
  <van-nav-bar title="收货地址" left-text="返回" left-arrow @click-left="back" />

  <van-address-list
    v-if="action == 'order'"
    v-model="active"
    :list="list"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="onChangeSelect"
  />

  <van-address-list
    v-else
    v-model="active"
    :list="list"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="onSelect"
  />
</template>

<script setup>
const { proxy } = getCurrentInstance();

let business = proxy.$cookies.get("business") ? proxy.$cookies.get("business") : {};

business = reactive(business);

const back = () => proxy.$router.go(-1);

// 判断来源 --> 是否确认订单
let action = proxy.$route.query.hasOwnProperty("action") ? proxy.$route.query.action : "";
action = ref(action);
// console.log(action);

let list = reactive([]);
let active = ref(0);

//挂载前生命周期
onBeforeMount(() => {
  request();
});

const request = async () => {
  var result = await proxy.$POST({
    url: "/address/index",
    params: { busid: business.id },
  });

  if (result.code && result.data) {
    var address = result.data.map((item) => {
      if (item.status == "1") {
        active.value = item.id;
      }

      return {
        id: item.id,
        name: item.consignee,
        tel: item.mobile,
        address: `${item.region_text} ${item.address}`,
        isDefault: item.status == "1" ? true : false,
      };
    });

    list.push(...address);
  }
};

const onAdd = () => {
  proxy.$router.push("/address/add");
};

const onEdit = (item) => {
  proxy.$router.push({
    path: "/address/edit",
    query: { id: item.id },
  });
};

const onSelect = async (item) => {
  if (item.isDefault) {
    proxy.$fail("已经是默认地址");
    return false;
  }

  var data = {
    id: item.id,
    busid: business.id,
  };

  var result = await proxy.$POST({
    url: "/address/check",
    params: data,
  });

  if (result.code == "0") {
    proxy.$fail(result.msg);
    return false;
  } else {
    list.map((value) => {
      value.isDefault = false;
      value.id === data.id && (item.isDefault = true);
    });
  }
};

// 订单选中的收货地址
const onChangeSelect = (val) => {
  let data = {
    id: val.id,
    name: val.name,
    tel: val.tel,
  };
  proxy.$cookies.set("address", data);
  back();
};
</script>
